<?php

use app\modules\Admin\models\membermoneylogModel;
use app\service\commission;
use app\service\tuike;
use Illuminate\Database\Capsule\Manager as DB;

#[默认控制器]
class IndexController extends CommonController
{
    protected $authExcept = ['index', 'init', 'ceshi','orderTongji','shifang','weixinInfo', 'richtext', 'custom', 'asyncPages', 'template', 'upload', 'checkVisitPassword','ceshifang','monthorder','monthfanyong','days60'];

    public function indexAction()
    {
        redirect('/h5');
        json(['code' => 1, 'msg' => 'welcome']);
    }

    public function ceshiAction(){
        $this->member[0] = 53;
        $this->member[0] = 52;
        $member_info = (new \memberModel)->where(['id'=>$this->member[0]])->first();
        $info        = DB::table('goods')->where(['id'=>993])->first();
        $parent_member_info =  (new \memberModel)->where(['id'=>$this->member[0]])->first();
        if($info){
            $arr  = explode(',', $info->category_ids);
            if(!empty($arr[0])){
                $vip_cate    = \categoryModel::where(['id'=>219])->first();
                $cate_id     = $arr[0];

                if($parent_member_info->is_jdr == 1){
                    if($cate_id == 219){
                        $this->shangji_jifen($parent_member_info,$vip_cate);
                    }else if($cate_id==218 || $cate_id==277 || $cate_id==278 || $cate_id==279 || $cate_id==280){
                        $cate_info = \categoryModel::where(['id'=>$cate_id])->first();
                        $commission      = $this->total_fee*$cate_info->zhitui;//酒达人直推
                        $this->shangjimoney($parent_member_info,$commission);
                    }
                }elseif($member_info->is_jdr == 1 && $parent_member_info->is_vip == 1 || $member_info->is_vip == 1 && $parent_member_info->is_vip == 1){
                    $this->shangji_jifen($parent_member_info,$vip_cate);
                }
            }
        }
        exit();

        $ids = 11;
        $items = \orderitemModel::where('order_id', $ids)->get();
        $member = (new \memberModel)->where('id', 1)->first();
        $commission = '1000.00'*"0.15";
        foreach ($items as $item) {
            $logRow = [
                'member_id' =>  $member->id,
                'event'     =>  "jdr",
                'event_id'  =>  $ids,
                'before'    =>  $member->money,
                'money'     =>  $commission,
                'after'     =>  $member->money + $commission,
                'remark'    =>  '分佣到账，订单ID：'.$item->order_id,
                'oper_type' =>  '系统',
                'oper_id'   =>  0,
                'created_at'=>  date('Y-m-d H:i:s')
            ];
            membermoneylogModel::insert($logRow);
            $member->increment('money', $commission);
        }


    }


    public function orderTongjiAction(){
        set_time_limit(0);
        $start = date('Y-m-d').' 00:00:00';
        $end   = date('Y-m-d').' 23:59:59';
        $money  = DB::table('order')->where('type','=','goods')->where('pay_type','<>','score')->where('status','>=',1)->whereBetween('created_at', [$start, $end])->sum('goods_amount');

        $money_tow = DB::table('member_zmd_apply')->where('agent_fee_pay_status','=',1)->whereBetween('created_at', [$start, $end])->sum('agent_fee');
        $money = $money+$money_tow;

        //返利基金：营业额的10%，后台需要有模块显示，返利者平均分配
        //3.1 储备金：当日返利基金的50%用于储备金，50%进入次日返利基金中，参与次日返利
        //3.2 储备金可以手动转入返利基金中，后台需有显示
        $money = $money*0.1;

        $res = DB::table('order_bonus')->whereBetween('created_at',  [$start, $end])->count();
        if(!$res){
            $ciri_money                 = $money/2;
            $inser_arr['money']         = $inser_arr['standby_money'] = $ciri_money;
            $inser_arr['created_at']    = date('Y-m-d H:i:s');
            $remaining = DB::table('order_bonus_remaining')->first();
            if($remaining){
                $up['money']          = $remaining->money + $ciri_money;
                $up['standby_money']  = $remaining->standby_money + $ciri_money;
                DB::table('order_bonus_remaining')->where(['id'=>$remaining->id])->update($up);
            }else{
                DB::table('order_bonus_remaining')->insert($inser_arr);
            }
            $arr['money']     = $tow_arr['money'] =  $ciri_money;//应分返利金
            $arr['all_money'] = $money;//总返利金
            $arr['created_at'] = $arr['created_at'] = date('Y-m-d H:i:s');
            DB::table('order_bonus')->insertGetId($arr);
            $tow_arr['memo']  = "每日结算统计";
            DB::table('order_bonus_reserve')->insertGetId($tow_arr);
            DB::table('order_bonus_rebate')->insertGetId($tow_arr);
        }
    }

    public function memberdividendAction($money,$ids){
        $memberModel = new \memberModel();
        $member =  $memberModel->select(['id','people'])->orderBy('id', 'asc')->get();
        if($member){
            $num   = $member->count();
            $money = round($money/$num,2);
            if($money<=0){
                echo '金额<0不产生分佣';
                return;
            }
            foreach ($member as $k=>$v){
                (new \memberModel)->money($money,$v->id,'orderdividend',$ids,'每日分红');
                $commission = $money;
                if($v->people < $money){
                    $commission = $v->people;
                }
                (new \memberModel)->people(-$commission, $v->id, 'orderaward', $ids, '每日分红转化');
            }
        }
    }

    public function digui($id,$money){
        $memberpeopleModel = new memberpeopleModel();
        $info              =  $memberpeopleModel->where(['member_id'=>$id,'status'=>1])->orderBy('id', 'ASC')->first();
        if($info){
            $upmoney       = $info->money+$money;
            if($upmoney < 0){
                $info->money  = 0;
                $info->status = 2;
                $info->save();
                return $this->digui($id,$upmoney);
            }else if($upmoney == 0){
                $info->money  = 0;
                $info->status = 2;
            }
            $info->money  = $upmoney;
            $info->save();
        }
    }

    /**
     * 月订单金额统计
     */

    public function monthorderAction(){
        $model       = new ordermonthModel();
        $start       = date('Y-m-01',strtotime(date('Y-m-d'))).' 00:00:01';
        $end         = date('Y-m-d',strtotime("{$start} +1 month -1 day")).' 23:59:59';
        $tongji_info = $model->whereBetween('created_at', [$start, $end])->first();
        $money  = DB::table('order')->where('type','=','goods')->where('status','>=',1)->whereBetween('created_at', [$start, $end])->sum('total_amount');
        $num  = DB::table('order')->where('type','=','goods')->where('status','>=',1)->whereBetween('created_at', [$start, $end])->count();
        if(!$tongji_info){
            $inser['money'] = $money;
            $inser['num']   = $num;
            $inser['created_at'] = date('Y-m-d H:i:s');
            $model->insert($inser);
        }else{
            $tongji_info->money      = $money;
            $tongji_info->num        = $num;
            $tongji_info->updated_at = date('Y-m-d H:i:s');
            $tongji_info->save();
        }
        echo "操作成功";
    }

    /**
     * 月返佣统计
     */

    public function monthfanyongAction(){
        $start       = date('Y-m-01',strtotime(date('Y-m-d'))).' 00:00:01';
        $end         = date('Y-m-d',strtotime("{$start} +1 month -1 day")).' 23:59:59';
       $data = DB::table('order')->where('type','=','goods')->where('status','>=',1)->whereBetween('created_at', [$start, $end])->pluck('id');
        $gudongModel = new gudongrewardModel();
        $gudongMoney   = $gudongModel->whereIn('order_id',$data)->sum('commission');
        $dailiMoney    = agentrewardModel::whereIn('order_id',$data)->sum('commission');
        $tuikeMoney    = tuikerewardModel::whereIn('order_id',$data)->sum('commission');
        $shifangMoney  = \membermoneylogModel::where('remark','每日释放分红')->whereBetween('created_at', [$start, $end])->sum('money');
        $model       = new fanyongmonthModel();
        $tongji_info = $model->whereBetween('created_at', [$start, $end])->first();
        if(!$tongji_info){
            $inser['gudong_money']  = $gudongMoney;
            $inser['daili_money']   = $dailiMoney;
            $inser['tuike_money']   = $tuikeMoney;
            $inser['shifang_money'] = $shifangMoney;
            $inser['created_at']    = date('Y-m-d H:i:s');
            $model->insert($inser);
        }else{
            $tongji_info->gudong_money       = $gudongMoney;
            $tongji_info->daili_money        = $dailiMoney;
            $tongji_info->tuike_money        = $tuikeMoney;
            $tongji_info->shifang_money      = $shifangMoney;
            $tongji_info->updated_at         = date('Y-m-d H:i:s');
            $tongji_info->save();
        }
        echo "操作成功";
    }

    public function ceshifangAction(){
//        echo "-------------";exit();

        $memberpeopleModel = new memberpeopleModel();
        $user_id = 3;
        $goods_id = 985;
        $event_id = 12;
        $score    = -1000;
        $info = $memberpeopleModel->where(['member_id'=>$user_id,'goods_id'=>$goods_id,'order_id'=>$event_id])->first();
        if($info){
            $this->digui($user_id,$score);
        }
//        dump($info);
exit();
        $data  = DB::table('member_zgyj')->where('day','<',60)->orderBy('id', 'DESC')->get()->toArray();
        if($data){
            $day = 60;
            $memberModel = new \memberModel();
            $num = 0;
            foreach ($data as $k=>$v){
//                var_dump($v->money);
                $money = round($v->money / $day,2);
                $member = (new \memberModel)->where('id', $v->member_id)->first();
//                dump($money);
//                dump($member->people);
//                dump($v->member_id);
                if($member->people >= $money){
//                    echo "222222222222222222";
//                    $r     = $memberModel->money($money,$v->member_id,'orderdividend',$v->id,'每日释放分红');
//                    if($r){
                        $up['day']        = $v->day+1; //已分天数
                        $up['day_money']  = $v->day_money + $money;//累计分红
                        $up['updated_at'] = strtotime(date("Y-m-d"))+86400;
                        dump($up);
//                        $r = DB::table('member_zgyj')->where(['id'=>$v->id])->update($up);
//                        if($r){
//                            $num +=1;
//                        }
//                        $memberModel->people(-$money, $member->id, 'orderaward', $v->id, '每日释放分红扣除');
//                    }
                }else{
//                    dump($v->member_id);
//                    echo "-------------";
                    $up['status'] = 2;
//                    DB::table('member_zgyj')->where(['id'=>$v->id])->update($up);
                }

            }
//            echo '处理数据'.$num;
        }else{
            echo "无数据";
        }
    }


    public function shifangAction(){
        $data  = DB::table('member_zgyj')->where('updated_at','<',time())->where('status','=',1)->where('day','<',60)->orderBy('id', 'DESC')->get()->toArray();
        if($data){
            $day = 60;
            $memberModel = new \memberModel();
            $num = 0;
            foreach ($data as $k=>$v){
                $money = round($v->money / $day,2);
                $member = (new \memberModel)->where('id', $v->member_id)->first();
                if($member->people >= $money){
                    $r     = $memberModel->money($money,$v->member_id,'orderdividend',$v->id,'每日释放分红');
                    if($r){
                        $up['day']        = $v->day+1; //已分天数
                        $up['day_money']  = $v->day_money + $money;//累计分红
                        $up['updated_at'] = strtotime(date("Y-m-d"))+86400;
                        $r = DB::table('member_zgyj')->where(['id'=>$v->id])->update($up);
                        if($r){
                            $num +=1;
                        }
                        $memberModel->people(-$money, $member->id, 'orderaward', $v->id, '每日释放分红扣除');
                    }
                }else{
                    $up['status'] = 2;
                    DB::table('member_zgyj')->where(['id'=>$v->id])->update($up);
                }

            }
            echo '处理数据'.$num;
        }else{
            echo "无数据";
        }
    }


    //60天分红

    public function days60Action(){

        $data        = DB::table('order_bonus_remaining')->where('money','>',0)->first();
        $memberModel = new \memberModel();
        $memberData  =  $memberModel->where('people','>',0)->select(['id','people'])->orderBy('id', 'asc')->get();
        if($data && $memberData->count() > 0){

            $money = round($data->money/$memberData->count(),2);
            $num = 0;
            $kou_money  = 0;
            foreach ($memberData as $k=>$v){
                if($v->people < $money){
                    $money = $v->people;
                }
                $kou_money+=$money;
                $memberModel->money($money,$v->id,'orderdividend',0,'60天分红');
                $memberModel->people(-$money, $v->id, 'fenhong', 0, '60天分红');
                $num +=1;
            }
            if($kou_money){
                $money = $data->money - $kou_money;
                DB::table('order_bonus_remaining')->where(['id'=>$data->id])->update(['money'=>$money]);
            }

            echo '处理数据'.$num;
        }else{
            echo "无数据";
        }
    }

    // 初始化商城数据
    public function initAction()
    {
        $platform = getHeader('platform'); // 获取平台标识
        if (!in_array($platform, ['H5', 'App', 'wxMiniProgram', 'wxOfficialAccount'])) {
            throw new Exception('请使用正确客户端访问');
        }

        $data = \app\service\config::get('', $platform);

        json(['code' => 1, 'msg' => '初始化数据', 'data' => $data]);
    }

    public function weixinInfoAction()
    {
        json(['code' => 1, 'msg' => '微信公众号', 'data' => \app\service\config::get('wechat')]);
    }

    public function richtextAction()
    {
        $id = $this->get('id');
        json(['code' => 1, 'msg' => '富文本', 'data' => pagesModel::find($id)]);
    }

    public function customAction()
    {
        $custom_id = $this->get('custom_id');
        $decorate = decorateModel::find($custom_id);
        if (!$decorate) {
            throw new Exception('未找到自定义页面');
        }
        $decorate->template = decorateModel::getCustomDecorate($custom_id);
        json(['code' => 1, 'msg' => '自定义模板数据', 'data' => $decorate]);
    }

    // 同步前端所有页面链接
    public function asyncPagesAction()
    {
        json(['code' => 1, 'msg' => 'ok']);
    }

    // 商城模板数据
    public function templateAction()
    {
        $get = $this->get();
        $platform = getallheaders()['Platform'];
        if (isset($get['shop_id']) && $get['shop_id'] != 0) {
            $template = decorateModel::getCurrentPlatformDecorate('preview', $get['shop_id']);
        } else {
            $template = decorateModel::getCurrentPlatformDecorate($platform);
        }
        json(['code' => 1, 'msg' => '模板数据', 'data' => $template]);
    }

    // 上传
    public function uploadAction()
    {
        $file = $this->getFiles('file');
        $target = $this->input('target', 'image');
        json(['code' => 1, 'msg' => '', 'data' => \app\service\cdn::upload($file, $target)]);
    }

    public function expressAction()
    {
        $data = DB::table('express')->select(['name', 'code'])->orderBy('weigh', 'desc')->get();
        json(['code' => 1, 'msg' => '', 'data' => $data]);
    }

    public function checkVisitPasswordAction()
    {
        $password = $this->get('password');
        $config = configModel::where('type', 1)->where('key', 'access_password')->value('value');
        if (!empty($config) && $password == $config) {
            json(['code' => 1]);
        } else {
            json(['code' => 0, 'msg' => '系统访问密码错误']);
        }
    }

    // 检测APP版本
    public function checkVersionAction()
    {
        $appid   = $this->input("appid");
        $version = $this->input("version"); //客户端版本号
        $rsp     = ["ret" => 3]; //默认返回值，不需要升级
        if (isset($appid) && isset($version)) {
            if ($appid === "__UNI__05D8A3F") { //校验appid
                if ($version < "2.0.6") {
                    $rsp["ret"]         = 0;
                    $rsp["msg"]         = "1.界面与操作流程优化\r\n2.当前版本2.0.6";
                    $rsp["android_url"] = "http://stjk.zmssp.cn/app/shuangte.apk";
                    $rsp["ios_url"]     = "itms-apps://itunes.apple.com/cn/app/";
                }
            }
        }
        json($rsp);
    }

}
